package com.websocket.example.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.websocket.example.config.socket.WebSocketServer;
import com.websocket.example.domain.Users;
import com.websocket.example.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.concurrent.atomic.AtomicInteger;

@Controller
public class DemoController {

    @Autowired
    private IUserService userService;

    @Autowired
    private WebSocketServer webSocketServer;

    private static AtomicInteger atomicInteger = new AtomicInteger(0);

    /**
     * 跳转到websocketDemo.html页面，携带自定义的cid信息。
     * http://localhost:8555/toWebSocketDemo/user-1
     *
     * @param cid
     * @param model
     * @return
     */
    @GetMapping("/toWebSocketDemo/{cid}")
    public String toWebSocketDemo(@PathVariable String cid, Model model) {
        model.addAttribute("cid", cid);
        return "websocketDemo";
    }


    @GetMapping("/toWebSocketDemo2/{cid}")
    public String toWebSocketDemo2(@PathVariable String cid, Model model) {
        model.addAttribute("cid", cid);
        return "websocketDemo2";
    }

    /**
     * 定时向客户端推送消息
     *
     * @throws Exception
     */
    @Scheduled(cron = "0/5 * * * * ?")
    private void configureTasks() throws Exception {
        Page<Users> usersPage = userService.selectList(1, atomicInteger.get(), 3);
        atomicInteger.incrementAndGet();
        webSocketServer.sendToAll(JSON.toJSONString(usersPage.getRecords()));
    }

}
